<template>
    <div
        class="page_root"
        :key="queryUpdateFlag"
        data-page-name="项目概览（一级）"
        data-page-identification="n_4migtos9ub"
    >
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_mtd7ux3tpj 自定义模板_suyklv3uvt -->
            <!--          编辑产品团队-->
            <a-modal
                v-model:visible="state.editTeamVisible"
                title="编辑团队成员"
                width="800px"
                @ok="handleSubmitEditTeam"
                @cancel="cancelEditTeam"
                :ok-button-props="{ loading: state.editTeamLoading }"
                destroy-on-close
                :mask-closable="false"
                :keyboard="false"
                centered
                :body-style="{
                    maxHeight: '800px',
                    overflowY: 'auto'
                }"
            >
                <div class="edit-team-form">
                    <div class="pj-title">
                        <div class="pj-title-son">团队成员</div>
                    </div>
                    <div class="extent-role">
                        <a-form :model="state.editTeamForm" ref="editTeamRef">
                            <a-row :gutter="24">
                                <a-col :span="12" v-for="(item, index) in state.editTeamForm.roleList" :key="index">
                                    <a-form-item
                                        :label="item.role"
                                        :name="['roleList', index, 'userList']"
                                        :rules="{
                                            required: item.mandatory,
                                            message: `请选择${item.role}`,
                                            trigger: 'blur'
                                        }"
                                        :labelCol="{ span: 24 }"
                                        :wrapperCol="{ span: 24 }"
                                    >
                                        <a-select
                                            :options="state.peopleList"
                                            mode="multiple"
                                            :allowClear="true"
                                            :dropdownMatchSelectWidth="true"
                                            :showSearch="true"
                                            :filterOption="
                                                (input, option) => {
                                                    return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                }
                                            "
                                            :fieldNames="{
                                                label: 'name',
                                                value: 'name'
                                            }"
                                            :showArrow="true"
                                            v-model:value="state.editTeamForm.roleList[index].userList"
                                        />
                                    </a-form-item>
                                </a-col>
                            </a-row>
                        </a-form>
                    </div>
                </div>
            </a-modal>
            <!--          编辑产品团队-->
            <div class="overview-one">
                <div class="inner-div">
                    <div class="base-data-title">
                        <div class="title">基本信息</div>
                        <a-button
                            type="primary"
                            ghost
                            @click="handleEditBase"
                            size="small"
                            v-permission="'50001252_vid_h9jrxs0lc7'"
                            :loading="state.baseSaveLoading"
                            >{{ state.baseEditStatus ? '保存' : '编辑' }}</a-button
                        >
                    </div>
                    <div class="base-date-content">
                        <a-descriptions
                            ref="baseDateRef"
                            bordered
                            size="small"
                            :column="4"
                            :label-style="{ width: baseLabelWidth + 'px', backgroundColor: '#f2f6fc' }"
                            :content-style="{
                                maxWidth: baseValueMaxWidth + 'px',
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis'
                            }"
                        >
                            <a-descriptions-item label="产品名称">
                                <template v-if="state.baseEditStatus">
                                    <a-textarea v-model:value="state.projectDetail.projectName" />
                                </template>
                                <template v-else>
                                    <span :title="state.projectDetail.projectName">{{
                                        state.projectDetail.projectName
                                    }}</span></template
                                >
                            </a-descriptions-item>
                            <a-descriptions-item label="产品简称">
                                <template v-if="state.baseEditStatus">
                                    <a-textarea
                                        maxlength="10"
                                        show-count
                                        v-model:value="state.projectDetail.projectCode"
                                    />
                                </template>
                                <template v-else>
                                    <span :title="state.projectDetail.projectCode">{{
                                        state.projectDetail.projectCode
                                    }}</span></template
                                >
                            </a-descriptions-item>
                            <a-descriptions-item label="产品级别">
                                <template v-if="state.baseEditStatus">
                                    <a-select
                                        style="width: 100%"
                                        :options="state.levelList"
                                        :showSearch="true"
                                        :placeholder="'请选择'"
                                        :allowClear="true"
                                        v-model:value="state.projectDetail.level"
                                    />
                                </template>
                                <template v-else>
                                    <span :title="state.projectDetail.level">{{ state.projectDetail.level }}</span>
                                </template>
                            </a-descriptions-item>
                            <a-descriptions-item label="产品项目阶段">
                                <template v-if="state.baseEditStatus">
                                    <a-select
                                        style="width: 100%"
                                        :options="state.stageList"
                                        :showSearch="true"
                                        :placeholder="'请选择'"
                                        :allowClear="true"
                                        v-model:value="state.projectDetail.stage"
                                    />
                                </template>
                                <template v-else>
                                    <span :title="state.projectDetail.stage"> {{ state.projectDetail.stage }}</span>
                                </template>
                            </a-descriptions-item>
                        </a-descriptions>
                    </div>
                    <div class="view-data-title">
                        <div class="title">产品概述</div>
                        <a-button
                            type="primary"
                            ghost
                            @click="handleEditView"
                            size="small"
                            :loading="state.viewSaveLoading"
                            v-permission="'50001252_vid_0q2g17vhe1'"
                            >{{ state.viewEditStatus ? '保存' : '编辑' }}</a-button
                        >
                    </div>
                    <div class="view-date-content">
                        <a-descriptions
                            ref="viewDateRef"
                            bordered
                            size="small"
                            :column="1"
                            :label-style="{ width: viewLabelWidth + 'px', backgroundColor: '#f2f6fc' }"
                            :content-style="{
                                maxWidth: viewValueMaxWidth + 'px',
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis'
                            }"
                        >
                            <a-descriptions-item label="产品背景">
                                <template v-if="state.viewEditStatus">
                                    <a-textarea v-model:value="state.projectDetail.background" />
                                </template>
                                <template v-else>
                                    <span :title="state.projectDetail.background">{{
                                        state.projectDetail.background
                                    }}</span></template
                                >
                            </a-descriptions-item>
                            <a-descriptions-item label="产品用户群体介绍">
                                <template v-if="state.viewEditStatus">
                                    <a-textarea v-model:value="state.projectDetail.userGroupIntroduction" />
                                </template>
                                <template v-else
                                    ><span :title="state.projectDetail.userGroupIntroduction">{{
                                        state.projectDetail.userGroupIntroduction
                                    }}</span></template
                                >
                            </a-descriptions-item>
                            <a-descriptions-item label="用户痛点">
                                <template v-if="state.viewEditStatus">
                                    <a-textarea v-model:value="state.projectDetail.painPoint" />
                                </template>
                                <template v-else>
                                    <span :title="state.projectDetail.painPoint">{{
                                        state.projectDetail.painPoint
                                    }}</span></template
                                >
                            </a-descriptions-item>
                        </a-descriptions>
                    </div>
                    <div class="team-data-title">
                        <div class="title">产品团队</div>
                        <a-space>
                            <a-button
                                type="primary"
                                ghost
                                size="small"
                                @click="handleShowEditTeam"
                                v-permission="'50001252_vid_ipp2vv3d30'"
                                >编辑</a-button
                            >
                        </a-space>
                    </div>
                    <div class="team-data-content">
                        <div class="table-box">
                            <a-table
                                :columns="teamColumns"
                                :data-source="state.projectDetail.projectExtendsRoleList"
                                bordered
                                :scroll="{ y: state.tableHeight }"
                                :pagination="false"
                            />
                        </div>
                    </div>
                </div>
            </div>
            <!-- end vid_mtd7ux3tpj 自定义模板_suyklv3uvt -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        },
        'useProjectId': {
            type: [String, Number],
            default: undefined
        },
        activeKey: String,
        refreshCount: Number
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    function checkRequired(value, msg = '必填项缺失') {
        if (value === undefined || value === null || value === '') {
            message.warning(msg) // 这里用 Antd 的 message，也可以改成 console.error 或 throw Error
            return false
        }
        return true
    }
    const baseDateRef = ref(null)
    const viewDateRef = ref(null)
    const baseLabelWidth = 150 // 固定 label 宽度
    const viewLabelWidth = 150 // 固定 label 宽度
    const baseValueMaxWidth = ref(200) // 动态计算 value 最大宽度
    const viewValueMaxWidth = ref(200) // 动态计算 value 最大宽度
    const baseColumn = 4 // 一行有几个字段对
    const viewColumn = 1 // 一行有几个字段对

    function calcValueWidth() {
        if (!baseDateRef.value) return
        const baseTotalWidth = baseDateRef.value.clientWidth
        const totalBaseLabelWidth = baseColumn * baseLabelWidth
        const totalBaseValueWidth = baseTotalWidth - totalBaseLabelWidth - 60 // 预留 padding/边框
        baseValueMaxWidth.value = Math.floor(totalBaseValueWidth / baseColumn)
        if (!viewDateRef.value) return
        const viewTotalWidth = viewDateRef.value.clientWidth
        const totalViewLabelWidth = viewColumn * viewLabelWidth
        const totalViewValueWidth = viewTotalWidth - totalViewLabelWidth - 60 // 预留 padding/边框
        baseValueMaxWidth.value = Math.floor(totalViewValueWidth / viewColumn)
    }
    onMounted(() => {
        calcValueWidth()
        calcTableHeight()
        window.addEventListener('resize', calcValueWidth)
        window.addEventListener('resize', calcTableHeight)
    })
    onBeforeUnmount(() => {
        window.removeEventListener('resize', calcValueWidth)
        window.removeEventListener('resize', calcTableHeight)
    })
    const headerOffset = ref(430)
    const calcTableHeight = () => {
        state.tableHeight = window.innerHeight - 180 - headerOffset.value
    }
    watch(
        () => [props.useProjectId, props.activeKey, props.refreshCount],
        val => {
            if (props.useProjectId) {
                getData()
                getLevelList()
                getStageList()
            }
        },
        { immediate: true }
    )
    const state = reactive({
        baseEditStatus: false,
        viewEditStatus: false,
        viewSaveLoading: false,
        baseSaveLoading: false,
        projectDetail: {},
        teamData: [],
        levelList: [],
        stageList: [],
        peopleList: [],
        editTeamVisible: false,
        editTeamLoading: false,
        tableHeight: 350,
        editTeamForm: {
            roleList: []
        }
    })
    // 获取字典
    function getStageList() {
        get('/solution-ppm-basic-data/api/v1/dictionary/search/CYXM.CPJD').then(data => {
            state.stageList = data.data.map(item => {
                return {
                    label: item.itemName,
                    value: item.itemName
                }
            })
        })
    }
    function getLevelList() {
        get('/solution-ppm-basic-data/api/v1/dictionary/search/CYXM.CPJB').then(data => {
            state.levelList = data.data.map(item => {
                return {
                    label: item.itemName,
                    value: item.itemName
                }
            })
        })
    }
    async function getData() {
        const url = `/solution-ppm/api/v2/built-in-system-ppm/platform_product/product_project/${props.useProjectId}`
        return await get(url)
            .then(async resp => {
                Object.assign(state.projectDetail, resp.data)
                return resp
            })
            .catch(async e => {
                return Promise.reject(e)
            })
            .finally(async () => {})
    }
    const emit = defineEmits(['getTreeData'])
    //     编辑
    async function handleEditBase() {
        if (!checkRequired(props.useProjectId, '请选择产品')) return

        if (!state.baseEditStatus) {
            state.baseEditStatus = true
        } else {
            const requiredFields = [
                { key: 'projectName', msg: '请输入产品名称' },
                { key: 'level', msg: '请选择产品级别' },
                { key: 'stage', msg: '请选择产品项目阶段' }
            ]

            for (const { key, msg } of requiredFields) {
                if (!state.projectDetail[key]) {
                    message.info(msg)
                    return
                }
            }
            const success = await handleEditProjectDetail('base', true)
            if (success) {
                state.baseEditStatus = false
                getData()
            }
        }
    }

    async function handleEditView() {
        if (!checkRequired(props.useProjectId, '请选择产品')) return
        if (!state.viewEditStatus) {
            state.viewEditStatus = true
        } else {
            const success = await handleEditProjectDetail('view', true)
            if (success) {
                state.viewEditStatus = false
                getData()
            }
        }
    }
    function getPlist() {
        get('/solution-ppm/api/v2/built-in-system-ppm/pmgf/get/allUser').then(data => {
            if (data.code === 200) {
                state.peopleList = data.data.userDtoList
            } else {
                message.error('获取用户列表失败！')
            }
        })
    }
    const loadingMap = {
        base: 'baseSaveLoading',
        view: 'viewSaveLoading',
        team: 'editTeamLoading'
    }
    async function handleEditProjectDetail(type, flag) {
        state[loadingMap[type]] = true
        try {
            const data = await put('/solution-ppm/api/v2/built-in-system-ppm/platform_product', state.projectDetail)
            if (data.code !== 200) {
                message.error(data.message)
                getData()
                return false
            }
            message.success(data.message)
            if (flag) emit('getTreeData', { id: props.useProjectId })
            return true
        } catch (e) {
            return false
        } finally {
            state[loadingMap[type]] = false
        }
    }

    const teamColumns = ref([
        {
            title: '团队人员',
            dataIndex: '',
            align: 'center',
            children: [
                {
                    title: '角色',
                    dataIndex: 'role',
                    align: 'center',
                    width: 150,
                    ellipsis: true
                },
                {
                    title: '人员',
                    dataIndex: 'user',
                    align: 'center',
                    ellipsis: true
                }
            ]
        }
    ])
    function handleShowEditTeam() {
        if (!checkRequired(props.useProjectId, '请选择产品')) return
        state.editTeamForm.roleList = cloneDeep(state.projectDetail.projectExtendsRoleList)
        getPlist()
        state.editTeamVisible = true
    }
    const editTeamRef = ref(null)
    async function handleSubmitEditTeam() {
        editTeamRef.value
            .validate()
            .then(() => {
                state.editTeamLoading = true
                let roleList = state.editTeamForm.roleList
                state.projectDetail.projectExtendsRoleList = roleList
                state.projectDetail.projectExtendsRoleList.forEach(item => {
                    item.user = item.userList.join(',')
                })
                put('/solution-ppm/api/v2/built-in-system-ppm/platform_product', state.projectDetail)
                    .then(data => {
                        if (data.code !== 200) {
                            message.error(data.message)
                            return
                        }
                        message.success(data.message)
                        getData()
                        state.editTeamVisible = false
                    })
                    .finally(() => {
                        state.editTeamLoading = false
                    })
            })
            .catch(() => {
                //校验未通过执行这里
                const errorList = document.querySelectorAll('.ant3-form-item-has-error')
                errorList[0]?.scrollIntoView({
                    block: 'center',
                    behavior: 'smooth'
                })
            })
    }
    function cancelEditTeam() {
        state.editTeamVisible = false
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    /*样式*/
    .overview-one {
        padding: 3px;
        .inner-div {
            padding: 12px 24px;
            box-shadow: 0 0 10px #ebebeb;
            .base-data-title,
            .view-data-title,
            .team-data-title {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 12px;
                .title {
                    font-size: 16px;
                    height: 16px;
                    line-height: 16px;
                    font-weight: 600;
                    padding-left: 8px;
                    border-left: 4px solid #3875ff;
                }
            }
            .base-date-content,
            .view-date-content,
            .team-data-content {
                margin-bottom: 16px;
            }
        }
    }
    .pj-title {
        height: 30px;
        border-bottom: 1px solid #bfbfbf;
        margin-bottom: 16px;
    }

    .pj-title-son {
        font-size: 14px;
        color: #262626;
        letter-spacing: 0;
        font-weight: 600;
        border-left: 4px solid #3875ff;
        padding-left: 5px;
        height: 18px;
        line-height: 18px;
    }

    :deep(.edit-team-form .ant3-form-item-label) {
        width: 115px !important;
    }
    .table-box :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-weight: 400;
        color: #262626;
        border-bottom: 1px solid #d9d9d9;
        padding: 8px 16px;
        word-break: break-all;
    }
    /*样式*/
</style>
